package com.example.gateway.component;

import com.moon.common.model.entity.InterfaceInfo;
import com.moon.common.model.entity.User;
import com.moon.common.model.entity.UserInterfaceInfo;
import com.moon.common.service.InnerInterfaceInfoService;
import com.moon.common.service.InnerUserInterfaceInfoService;
import com.moon.common.service.InnerUserService;
import com.moon.moonclientsdk.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    //白名单
    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String INTERFACE_HOST = "http://localhost:8123";

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    /**
     * 预期是等模拟接口调用完成，才记录响应日志、调用次数+1。
     * 但现实是 chain.fitter 方法立刻返回了，直到 filter 过滤器 return 后才调用了模拟接口。
     * 原因是：chain.filter 是个异步操作
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 用户发送请求到 API 网关——已实现

        //2. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        String path = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求唯一标识:" + request.getId());
        log.info("请求路径:" + path);
        log.info("请求方法:" + method);
        log.info("请求参数:" + request.getQueryParams());
        log.info("请求来源地址:" + request.getRemoteAddress());
        String sourceAdress = request.getLocalAddress().getHostString();
        log.info("请求来源地址:" + sourceAdress);
        ServerHttpResponse response = exchange.getResponse();
        //3. 黑白名单:如果它这里不符合我们的请求来源地址(白名单)，我们就拒绝它访问
        if (!IP_WHITE_LIST.contains(sourceAdress)) {
            return handleNoAuth(response);
        }
        //4.用户鉴权（判断ak、sk是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        //TODO 实际是去数据库查是否已分配给用户 √
        //if (!"moon".equals(accessKey)){
        //    return handleNoAuth(response);
        //}
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);

        } catch (Exception e) {
            log.error("获取接口调用用户密钥失败", e);
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }

        //校验随机数
        if (Long.parseLong(nonce) > 10000) {
            return handleNoAuth(response);
        }
        // 时间戳：首次请求时间和当前时间间隔不超过5分钟
        Long currentTime = System.currentTimeMillis() / 1000;
        Long FIVE_MINUTES = 60 * 5L;
        assert timestamp != null;
        if ((currentTime - Long.parseLong(timestamp)) >= FIVE_MINUTES) {
            return handleNoAuth(response);
        }
        //TODo 实际情况是从数据库中查询出 secretKey √
        // 获取用户密钥
        String secretKey = invokeUser.getSecretKey();
        // 使用密钥对body进行签名
        String serverSign = SignUtil.getSign(body, secretKey);
        // 如果签名不存在或者签名不匹配，则返回无权限处理
        if (sign == null || !sign.equals(serverSign)) {
            return handleNoAuth(response);
        }
        //5. 请求的模拟接口是否存在？
        /**
         * TODO 从数据库中查询模拟接口是否存在，以及请求方法是否匹配? √
         * 因为网关项目没引入MyBatis等操作数据库的类库，如果该孩操作较为复杂，可以由backend增删改查项目提供接口，我们直接调用，不用再重复写逻辑了。
         */
        InterfaceInfo interfaceInfo = null;
        try {
            //从请求头接口路径和方法中获取到接口信息
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);

        } catch (Exception e) {
            log.error("获取模拟接口信息失败", e);
        }
        if (interfaceInfo == null) {
            return handleNoAuth(response);
        }
        //TODO 在发送请求前，网关需要判断接口是否还有调用次数 √
        Long userId = invokeUser.getId();
        Long interfaceInfoId = interfaceInfo.getId();
        UserInterfaceInfo userInterfaceInfo = innerUserInterfaceInfoService.getUserInterfaceInfo(userId, interfaceInfoId);
        if (userInterfaceInfo == null) {
            return handleNoAuth(response);
        }
        Integer leftNum = userInterfaceInfo.getLeftNum();
        if (leftNum <= 0) {
            log.error("接口调用次数已用完");
            return handleInvokeError(response);
        }
        //6. 请求转发，调用模拟接口
        //TODO 因为chain.filter 是个异步操作,直到 filter 过滤器 return 后才调用了模拟接口。需改进 √
//        Mono<Void> filter = chain.filter(exchange);
        //7. 响应日志
        return handleResponse(exchange, chain,userId , interfaceInfoId);
        //todo 8. 调用成功，接口调用次数+1 invokeConut
//        if (response.getStatusCode()== HttpStatus.OK) {
//            log.info("custom global filter全局过滤器...........");
//        }else {
//            //9. 调用失败，返回规范错误码500
//            return handleInvokeError(response);
//        }
//        return filter;
    }

    /**
     * 处理响应日志
     * 利用了装饰者设计模式,<font color="yellow">这段代码不用记</font>
     * 解决: filter 过滤器 return 后调用了模拟接口的异步操作问题
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long userId, long interfaceInfoId) {
        try {
            // 从交换机拿到原始response,我们现在需要对resonse进行增强
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓冲区工厂 拿到缓存数据
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        // 对象是响应式的
                        if (body instanceof Flux) {
                            // 我们拿到真正的body
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里面写数据
                            // 拼接字符串
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // TODO 7. 调用成功，接口调用次数+1 √
                                //快捷键ctrl+Alter+T
                                try {
                                    innerUserInterfaceInfoService.invokeInterfaceInfoCount(userId, interfaceInfoId);
                                } catch (Exception e) {
                                    log.error("调用接口次数+1失败", e);
                                }
                                // data从这个content中读取
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);// 释放掉内存
                                // 6.构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                String data = new String(content, StandardCharsets.UTF_8);// data
                                sb2.append(data);
                                log.info("响应结果：{}", data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            // 8.调用失败返回错误状态码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);// 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    /**
     * 执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 无权限
     */
    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        //通过设置响应状态码来拒绝请求
        response.setStatusCode(HttpStatus.FORBIDDEN);
        //结束请求
        return response.setComplete();
    }

    /**
     * 接口调用异常
     *
     * @param response
     * @return
     */
    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}